﻿using System;
using System.Linq;
using System.Web.UI;

namespace MyLib.Web {
	/// <summary>
	/// 
	/// </summary>
	public static class StateBagExtensions {
		/// <summary>
		/// Load value from state bag.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="states"></param>
		/// <param name="key"></param>
		/// <param name="defaultValue">Default value if there is no key in this state bag.</param>
		/// <returns></returns>
		public static T Get<T>(this StateBag states, string key, T defaultValue = default(T)) {
			if (states == null)
				return defaultValue;

			//var o =  states.Cast<System.Collections.DictionaryEntry>()
			//    .FirstOrDefault(item => string.Equals((string)item.Key, key, StringComparison.OrdinalIgnoreCase));

			var o = states[key];
			if (o == null)
				return defaultValue;

			return (T)Convert.ChangeType(o, typeof(T));
		}
	} // end of ViewStateExtensions.
}
